import { findSubCategoryFilter, findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
import { ref } from 'vue'

const useSubCate = () => {
  const route = useRoute()
  // 在setup中，获取路由对象
  const subCate = ref({})
  findSubCategoryFilter(route.params.id).then(data => {
    console.log('findSubCategoryFilter', data)

    // 1.给品牌加全部
    // 补充selected = false
    data.result.brands.forEach(it => { it.selected = false })
    data.result.brands.unshift({ id: null, name: '全部', selected: true })
    // 2.给属性加全部
    // 补充selected = false
    data.result.saleProperties.forEach(item => {
      item.properties.forEach(it => { it.selected = false })
      item.properties.unshift({ id: null, name: '全部', selected: true })
    })

    subCate.value = data.result
  })

  return { subCate }
}

const useLoadData = () => {
  const route = useRoute()
  // 请求参数
  let reqParams = {
    categoryId: route.params.id,
    inventory: null, // 是否只显示有库存
    onlyDiscount: null, // 是否只显示有优惠
    brandId: null, // 品牌名称
    attrs: [], // 商品属性
    sortField: null, // 排序类别
    sortMethod: null, // 排序的方式
    page: 1,
    pageSize: 20
  }

  const goodsList = ref([])
  const isFinished = ref(false)
  const isLoading = ref(false)
  const loadData = () => {
    isLoading.value = true
    findSubCategoryGoods(reqParams).then(data => {
      console.log('findSubCategoryGoods', data)
      // 1.新数据要追加到数组中
      goodsList.value.push(...data.result.items)
      // 2.页码加1
      reqParams.page++
      // 3.判断是否加载完成
      if (data.result.items.length === 0) {
        isFinished.value = true
      }
      isLoading.value = false
    })
  }
  // 筛选条件
  const hFilterChange = (filterParam) => {
    console.log('父组件收到了筛选条件', filterParam)
    // 1.更新条件
    // reqParams.brandId = filterParam.brandId
    // reqParams.attrs = filterParam.attrs
    reqParams = { ...reqParams, ...filterParam }
    // 2.重置页码,清空数据
    reqParams.page = 1
    goodsList.value = []
    isFinished.value = false
    // 3.重发请求
    loadData()
  }
  // 排序条件
  const hSortChange = (sortParam) => {
    console.log('父组件收到了排序条件', sortParam)
    // 1.更新条件
    // reqParams.inventory = sortParam.inventory
    // reqParams.onlyDiscount = sortParam.onlyDiscount
    reqParams = { ...reqParams, ...sortParam }
    // 2.重置页码,清空数据
    reqParams.page = 1
    goodsList.value = []
    isFinished.value = false
    // 3.重发请求
    loadData()
  }

  loadData()

  return { isFinished, isLoading, goodsList, hFilterChange, hSortChange, loadData }
}

export { useSubCate, useLoadData }
